package com.hxl.olympic.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hxl.okhttp.response.JsonResponseHandler;
import com.hxl.olympic.R;
import com.hxl.olympic.fragment.RegisterFragment;
import com.hxl.olympic.pojo.User;
import com.hxl.olympic.pojo.UserKey;
import com.hxl.olympic.util.Constant;
import com.xuexiang.xui.widget.toast.XToast;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;


public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.et_user)
    EditText etUser;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.img_display)
    ImageView imgDisplay;
    @BindView(R.id.tv_forget_pwd)
    TextView tvForgetPwd;
    @BindView(R.id.btn_login1)
    Button btnLogin1;
    @BindView(R.id.tv_switch1)
    TextView tvSwitch1;
    @BindView(R.id.tv_register1)
    TextView tvRegister1;
    @BindView(R.id.layout_user)
    LinearLayout layoutUser;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_sendCode)
    TextView tvSendCode;
    @BindView(R.id.btn_login2)
    Button btnLogin2;
    @BindView(R.id.tv_switch2)
    TextView tvSwitch2;
    @BindView(R.id.tv_register2)
    TextView tvRegister2;
    @BindView(R.id.layout_phone)
    LinearLayout layoutPhone;
    @BindView(R.id.tv_qq)
    TextView tvQq;
    @BindView(R.id.tv_wechat)
    TextView tvWechat;
    @BindView(R.id.tv_weibo)
    TextView tvWeibo;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    private boolean display = false;
    private String phone, code;
    private int time;
    private Timer timer;

    @Override
    public void initialize() {
        timer = new Timer();
    }

    @Override
    public void initView() {
        editor.putString("userInfo", "");
        editor.commit();
    }

    @Override
    public void initData() {
        tvTitle.setText(getResources().getString(R.string.login));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    @OnClick({R.id.img_back, R.id.img_display, R.id.tv_forget_pwd, R.id.btn_login1, R.id.tv_switch1, R.id.tv_register1, R.id.tv_sendCode, R.id.btn_login2, R.id.tv_switch2, R.id.tv_register2, R.id.tv_qq, R.id.tv_wechat, R.id.tv_weibo})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        startActivity(new Intent(context, MainActivity.class));
                    }
                }, 500);
                break;
            case R.id.btn_login1:
                login1();
                break;
            case R.id.btn_login2:
                login2();
                break;
            case R.id.tv_sendCode:
                sendCode();
                break;
            case R.id.tv_forget_pwd:
                break;
            case R.id.tv_switch1:
                layoutUser.setVisibility(View.GONE);
                layoutPhone.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_switch2:
                layoutUser.setVisibility(View.VISIBLE);
                layoutPhone.setVisibility(View.GONE);
                break;
            case R.id.tv_register1:
            case R.id.tv_register2:
                fragmentManager.beginTransaction().replace(R.id.layout_login, new RegisterFragment())
                        .addToBackStack(null)
                        .commit();
                break;
            case R.id.tv_qq:
                break;
            case R.id.tv_wechat:
                break;
            case R.id.tv_weibo:
                break;
            case R.id.img_display:
                if (display) {
                    etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    imgDisplay.setBackgroundResource(R.mipmap.ic_bly);
                    display = false;
                } else {
                    imgDisplay.setBackgroundResource(R.mipmap.ic_bmq);
                    etPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    display = true;
                }
                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (time == 0) {
                        timer.cancel();
                        tvSendCode.setText("获取验证码");
                        tvSendCode.setEnabled(true);
                        return;
                    }
                    tvSendCode.setText("重新获取(" + time + ")");
                    --time;
                    break;
            }
        }
    };

    private void sendCode() {
        phone = etPhone.getText().toString().trim();
        if (phone.equals("")) {
            XToast.info(context, "手机号输入为空!", Toast.LENGTH_SHORT).show();
            return;
        } else if (phone.length() < 11) {
            XToast.info(context, "请输入11位手机号!", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        System.out.println(code);
        params.put("code", code);
        tvSendCode.setEnabled(false);
        app.getOkHttpUtils().post(Constant.BASE_URL + Constant.sendCode, params, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                try {
                    JSONObject json = new JSONObject(response.toString());
                    if (json.getString("Message").equals("OK")) {
                        XToast.success(context, "短信验证码发送成功!", Toast.LENGTH_SHORT).show();
                        time = 60;
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                handler.sendEmptyMessage(1);
                            }
                        }, 0, 1000);
                    } else {
                        XToast.error(context, json.getString("Message"), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                XToast.error(context, "网络请求失败!", Toast.LENGTH_SHORT).show();
                tvSendCode.setEnabled(true);
                tvSendCode.setText("重新发送");
            }
        });
    }

    private void login1() {
        String user = etUser.getText().toString().trim();
        String pwd = etPwd.getText().toString().trim();
        if (user.equals("") || pwd.equals("")) {
            XToast.info(context, "账号或密码输入为空!", Toast.LENGTH_SHORT).show();
            return;
        } else if (user.length() < 6 || pwd.length() < 8) {
            XToast.info(context, "账号或密码过短!", Toast.LENGTH_SHORT).show();
            return;
        }
        UserKey key = new UserKey(user, pwd);
        String json = new Gson().toJson(key);
        dialog.show();
        app.getOkHttpUtils().post(Constant.BASE_URL + Constant.login, json, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                app.setUserInfo(new Gson().fromJson(response.toString(), (Type) User.class));
                editor.putString("userInfo", response.toString());
                editor.commit();
                XToast.success(context, "登录成功!", Toast.LENGTH_SHORT).show();
                LoginActivity.this.finish();
                startActivity(new Intent(context, MainActivity.class));
                dialog.cancel();
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                if (statusCode == 200) {
                    XToast.error(context, "账号或密码错误!", Toast.LENGTH_SHORT).show();
                } else {
                    XToast.error(context, "网络请求失败!", Toast.LENGTH_SHORT).show();
                }
                dialog.cancel();
            }
        });
    }

    private void login2() {
        phone = etPhone.getText().toString().trim();
        String inputCode = etCode.getText().toString().trim();
        if (phone.equals("") || inputCode.equals("")) {
            XToast.info(context, "手机号或验证码输入为空!", Toast.LENGTH_SHORT).show();
            return;
        } else if (phone.length() < 11 || inputCode.length() < 6) {
            XToast.info(context, "手机号或验证码长度不正确!", Toast.LENGTH_SHORT).show();
            return;
        } else if (!code.equals(inputCode)) {
            XToast.info(context, "验证码输入不正确!", Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        dialog.show();
        app.getOkHttpUtils().post(Constant.BASE_URL + Constant.selectUserByPhone, params, new JsonResponseHandler() {
            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                app.setUserInfo(new Gson().fromJson(response.toString(), (Type) User.class));
                editor.putString("userInfo", response.toString());
                timer.cancel();
                editor.commit();
                XToast.success(context, "登录成功!", Toast.LENGTH_SHORT).show();
                LoginActivity.this.finish();
                startActivity(new Intent(context, MainActivity.class));
                dialog.cancel();
            }

            @Override
            public void onFailure(int statusCode, String error_msg) {
                if (statusCode == 200) {
                    XToast.warning(context, "该手机号暂未注册!", Toast.LENGTH_SHORT).show();
                } else {
                    XToast.error(context, "网络请求失败!", Toast.LENGTH_SHORT).show();
                }
                dialog.cancel();
            }
        });
    }


}
